package com.xiayuanxing.gulimall.product.execption;


import com.xiayuanxing.common.execption.BizCodeEnume;
import com.xiayuanxing.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: gulimall
 * @description: 统一异常处理类
 * @author: 夏远兴
 * @create: 2020-04-28 23:01
 *集中处理所有异常
 **/
@Slf4j
@RestControllerAdvice(basePackages = "com.xiayuanxing.gulimall.product.controller")
public class GulimallExecptionControllerAdvice {

//    处理自定义的MethodArgumentNotValidException异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildExecption(MethodArgumentNotValidException e){

        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());

        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errorMap = new HashMap();

        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });

        return R.error(BizCodeEnume.VAILD_EXECPTION.getCode(),BizCodeEnume.VAILD_EXECPTION.getMsg()).put("data",errorMap);
    }

//    处理所有异常
    @ExceptionHandler(value = Throwable.class)
    public  R handleExecption(Throwable throwable){
        return R.error(BizCodeEnume.UNKNOW_EXECPTION.getCode(),BizCodeEnume.UNKNOW_EXECPTION.getMsg());
    }

}
